package com.tronsis.library.util;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;


import java.util.Locale;

/**
 * @author Ross@tronsis.com
 *         date: 2017/6/8.
 */

public class LanguageUtil {
    public static final String SYSTEM_LANGUAGE = "system_language";  //系统语言


    public static String getSystemLanguage(Context context){
        Locale locale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = context.getResources().getConfiguration().getLocales().get(0);
        } else {
            locale = context.getResources().getConfiguration().locale;
        }
        return locale.getLanguage();
    }

    public static void changeLanguage(Context context,String language){
        // 设置应用语言类型
        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        if (language.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(config, dm);

        // 保存设置语言的类型
        SharedPreferencesUtil.putString(context, SYSTEM_LANGUAGE, language);
    }

    /**
     * 获取当前设置语言
     */
    public static String getLanguage(Context context){
        Locale locale = Locale.getDefault();
        String language = locale.getLanguage();
        String mLanguage = SharedPreferencesUtil.getString(context, SYSTEM_LANGUAGE, language);
        return  mLanguage;
    }

}
